package com.ruoyi.common.utils.uuid;


import com.ruoyi.common.annotation.ConditionalExport;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Aspect
@Component
public class ExcelExportAspect {

   // @Around("execution(* com.ruoyi.common.utils.poi.ExcelUtil.exportExcel(..)) && target(ExcelUtil)")
    public Object handleExport(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        List<?> dataList = (List<?>) args[0];
        String sheetName = (String) args[1];
        Class<?> clazz = (Class<?>) args[2];
        HttpServletResponse response = (HttpServletResponse) args[3];

        // 获取条件参数(这里需要根据实际情况获取)
        Map<String, String> conditionParams = getConditionParams();

        // 动态处理数据
        List<Object> filteredData = new ArrayList<>();
        for (Object item : dataList) {
            Object filteredItem = filterFields(item, conditionParams);
            filteredData.add(filteredItem);
        }

        // 替换原始参数
        Object[] newArgs = new Object[]{filteredData, sheetName, clazz, response};
        return joinPoint.proceed(newArgs);
    }

    private Object filterFields(Object source, Map<String, String> conditionParams) {
        try {
            Object target = source.getClass().newInstance();
            Field[] fields = source.getClass().getDeclaredFields();

            for (Field field : fields) {
                field.setAccessible(true);
                ConditionalExport cond = field.getAnnotation(ConditionalExport.class);

                if (cond == null || conditionParams.get(cond.paramName()).equals(cond.expectedValue())) {
                    field.set(target, field.get(source));
                }
            }
            return target;
        } catch (Exception e) {
            throw new RuntimeException("动态过滤字段失败", e);
        }
    }

    private Map<String, String> getConditionParams() {
        // 这里需要根据实际情况获取条件参数
        // 可以从请求上下文、ThreadLocal等获取
        Map<String, String> params = new HashMap<>();
        params.put("excelTypeDidao", "yumihh"); // 示例值
        return params;
    }
}

